package main

import (
	"flag"
	"github.com/gordonklaus/portaudio"
	"log"
	"os"
)

var s = flag.Float64("s", 44100, "sample rate")

type echo struct {
	*portaudio.Stream
	buffer []float32
	i      int
}

func main() {
	flag.Parse()
	portaudio.Initialize()
	defer portaudio.Terminate()
	if h, err := portaudio.DefaultHostApi(); err != nil {
		log.Printf("leenux- Failed to initialize host: %v\n", err)
	} else {
		for _, d := range h.Devices {
			log.Printf("leenux- device : %v\n", d)
		}
		p := portaudio.LowLatencyParameters(h.Devices[2], nil)
		p.Input.Channels = 1
		//p.Input.Device.DefaultSampleRate = 8000
		p.SampleRate = *s
		p.FramesPerBuffer = 1200
		//log.Printf("leenux- input is:%v\n", p.Input.Device.)
		//e := &echo{buffer: make([]float32, 0)}
		in := make([]int16, 1200)
		if stream, err := portaudio.OpenStream(p, in); err != nil {
			log.Printf("leenux- Error opening stream: %v\n", err)
		} else {
			log.Printf("leenux- OK open stream\n")
			defer stream.Close()
			if err := stream.Start(); err != nil {
				log.Printf("leenux- Error starting stream: %v\n", err)
				return
			}
			defer stream.Stop()
			go func() {
				for {
					if err := stream.Read(); err != nil {
						log.Printf("leenux- Error reading from stream: %v\n", err)
						return
					}
					log.Printf("leenux- read %v bytes\n", in)
				}
			}()
		}
	}
	b := make([]byte, 1)
	os.Stdin.Read(b)
}
